import { useEffect } from 'react';
import { ConfigProvider } from 'antd';
import { NextPage } from 'next';
import './index.module.scss';
import '@/styles/globals.scss';

import ErrorBoundary from '@/components/ErrorBoundary'
import Layout from '@/components/layout';
import userStore from '@/store/userStore';

interface IProps {
  initialValue: Record<any, any>;
  Component: NextPage;
  pageProps: any;
}

function MyApp({ initialValue, Component, pageProps }: IProps) {
  const setUserInfo = userStore((state) => state.setUserInfo);

  useEffect(() => {
    setUserInfo(initialValue?.user?.userInfo);
  }, []);

  if ((Component as any).layout == 'invisible') {
    return (
      <ErrorBoundary>
        <ConfigProvider>
          <Component {...pageProps} />
        </ConfigProvider>
      </ErrorBoundary>
    )
  }

  return (
    <Layout>
      <ErrorBoundary>
        <ConfigProvider>
          <Component {...pageProps} />
        </ConfigProvider>
      </ErrorBoundary>
    </Layout>
  );
}

MyApp.getInitialProps = async ({ ctx }: any) => {
  const { userId, nickname, avatar } = ctx?.req?.cookies || {};

  return {
    initialValue: {
      user: {
        userInfo: {
          userId,
          nickname,
          avatar,
        },
      },
    },
  };
};

export default MyApp;
